package com.cms.common.spring;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Spring容器工具类（用来获取bean）.
 * 
 * <ul>
 * <li>需在applicationContext.xml中将此类配置bean</li>
 * </ul>
 */
public class SpringContextUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext;
	
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	/** 获取applicationContext. */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	/** 获取bean. */
	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}
	
	/** 获取类型为requiredType的对象，如果bean不能被类型转换，相应的异常将会被抛出. */
	public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		return applicationContext.getBean(name, requiredType);
	}
	
	/** 批量获取bean，names为逗号间隔的多个bean的name. */
	public static List<Object> getBeans(String names) throws BeansException {
		List<Object> os = new ArrayList<Object>();
		for (String name : names.split(",")) {
			os.add(getBean(name));
		}
		return os;
	}
	
	/** 批量获取类型为requiredType的对象，如果bean不能被类型转换，相应的异常将会被抛出，names为逗号间隔的多个bean的name. */
	public static <T> List<T> getBeans(String names, Class<T> requiredType) throws BeansException {
		List<T> ts = new ArrayList<T>();
		for (String name : names.split(",")) {
			ts.add(getBean(name, requiredType));
		}
		return ts;
	}
	
	/** 批量获取bean. */
	public static List<Object> getBeans(List<String> names) throws BeansException {
		List<Object> os = new ArrayList<Object>();
		for (String name : names) {
			os.add(getBean(name));
		}
		return os;
	}
	
	/** 批量获取类型为requiredType的对象，如果bean不能被类型转换，相应的异常将会被抛出. */
	public static <T> List<T> getBeans(List<String> names, Class<T> requiredType) throws BeansException {
		List<T> ts = new ArrayList<T>();
		for (String name : names) {
			ts.add(getBean(name, requiredType));
		}
		return ts;
	}

	/** 如果applicationContext包含一个与所给名称匹配的bean定义，则返回true. */
	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}
	 
	/** 判断bean是singleton还是prototype. */
	public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
		return applicationContext.isSingleton(name);
	}
	 
	/** 取得bean的类型. */
	public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
		return applicationContext.getType(name);
	}
	 
	/** 取得bean的别名(如果有). */
	public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
		return applicationContext.getAliases(name);
	}

}